package br.facet.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.facet.pojo.Marca;
import br.facet.utils.HibernateUtils;

public class MarcaDAO implements Serializable {

	public String obterMarca(String nome){

		Session sessao = null;
		Transaction tx = null;
		String retorno = null;

		try {
			sessao = HibernateUtils.getSession();
			tx = sessao.beginTransaction();
			Query sql = sessao.createSQLQuery("Select * from tbl_marca where nome = :nome").setParameter("nome", nome);

			if(sql.uniqueResult() == null){
				retorno = "inexistente";
			}
			else{

				retorno ="existe";
			}

			tx.commit();

		} catch (Exception e) {
			tx.rollback();
			retorno = "erro";
		} finally {
			if(sessao != null){
				try {
					sessao.close();					
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}

		}
		return retorno;
	}
	
	public List<Marca> listarMarcas(){

		List<Marca> listaDeMarca = new ArrayList<Marca>();

		Session sessao = null;
		Transaction tx = null;

		try {
			sessao = HibernateUtils.getSession();
			tx = sessao.beginTransaction();
			listaDeMarca = sessao.createCriteria(Marca.class).list();
			//tx.commit();

		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			if(sessao != null){
				try {
					sessao.close();					
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
		return listaDeMarca;
	}


	public void salvarMarca(Marca marca){

		Session sessao = null;
		Transaction tx = null;

		try {
			sessao = HibernateUtils.getSession();
			tx = sessao.beginTransaction();
			sessao.saveOrUpdate(marca);
			tx.commit();

		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			if(sessao != null){
				try {
					sessao.close();					
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}

	}

	public void excluirMarca(Marca marca) throws Exception {

		Session session = HibernateUtils.getSessionFactory().openSession();
		try {

			session.beginTransaction();
			session.delete(marca);
			session.getTransaction().commit();
		} 
		catch (Exception e) {
			session.getTransaction().rollback();
			throw new Exception("Erro ao excluir o Produto. Tente novamente.");
		} finally {
			session.close();
		}
	}
	
	public Marca load(Integer id) throws Exception {
		Marca result = null;
		Session session = HibernateUtils.getSessionFactory().openSession();
		try {
			result = (Marca) session.load(Marca.class, id);
		} 
		catch (Exception e) {
			session.getTransaction().rollback();
			throw new Exception("Erro ao carregar o Marca. Tente novamente.");
		} finally {
			session.close();
		}
		return result;
	}

}